﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Management;
using MCorder.motor;
using MCorder.efside;
using MCorder.control;
using System.Timers;


namespace MCorder.programUI
{
    public partial class MainForm : Form
    {
        string[] args;

        public MainForm(string[] argss)
        {
            this.args = argss;
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
        }

        private DevControl deviceCtrl = new DevControl();
        System.Timers.Timer daqTimer = new System.Timers.Timer();

        //数据记录链表
        //全数据记录
        List<float> position = new List<float>();
        List<float> ad = new List<float>();

        List<float> Ic_static_x = new List<float>();
        List<int> Ic_static_y = new List<int>();


        double clutchtorque = 0.3;

        //窗体初始化操作
        private void Form1_Load(object sender, EventArgs e)
        {
            InitChart();

            deviceCtrl.Init();

            timer1.Enabled = true;

            daqTimer.Enabled = true;

            readconfig();

            daqTimer.Interval = 89; //这个时间单位毫秒,比如10秒，就写10000 
            daqTimer.Elapsed += new ElapsedEventHandler(daqTimer_Elapsed);
        }

        double cur1, pos1, speed1;
        void daqTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            DevDataSet devData = new DevDataSet();
            if (deviceCtrl.GetData(ref devData))
            {
                if (drawCueve & (devData.pos > 0))
                {
                    position.Add((float)devData.pos);
                    ad.Add((float)(devData.cur));
                }
                //int a = devData.num_cur;
                //int b = devData.num_pos;
                //if(a>0&b>0)
                //{
                //    int aa = 0;
                //    if (a > b)
                //    {
                //        aa = b;
                //    }
                //    else
                //    {
                //        aa = a;
                //    }
                //    for (int i = 0; i < aa - 1; i++)
                //    {
                //        if (drawCueve)
                //        {
                //            position.Add((float)devData.pos);
                //            ad.Add((float)(devData.cur));
                //        }
                //    }
                //}
                cur1 = devData.cur;
                pos1 = devData.pos;
                speed1 = devData.speed;               
            }
            //Console.WriteLine("devData.num_cur=" + devData.num_cur);
            //Console.WriteLine("devData.num_pos=" + devData.num_pos);
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (iCount % 5 == 0)//10ms-->20hz刷新
            {
                zGraph1.f_Refresh();

                if (pos1 != 0 && cur1 != 0)
                {
                    label_curpos.Text = pos1.ToString("0.000");
                    label_curcur.Text = cur1.ToString("0.000");
                    toolStripStatusLabel_speed.Text = speed1.ToString("0.000");

                    Distance_Finish_chekck();
                }
            }
            iCount++;           
        }
        private void readconfig()
        {
            if (System.IO.File.Exists("config.ini"))
            {
                string[] readconfig = System.IO.File.ReadAllLines("config.ini");

                for (int ijk = 0; ijk < readconfig.Length; ijk++)
                {
                    string[] linebreak = readconfig[ijk].Split('=');
                    if (linebreak.Length > 1)
                    {
                        if (linebreak[0].Contains("static_interval"))
                        {
                            chart2.ChartAreas[0].AxisX.Interval = Convert.ToDouble(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("static_min"))
                        {
                            chart2.ChartAreas[0].AxisX.Minimum = Convert.ToDouble(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("static_max"))
                        {
                            chart2.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("distace_lim"))
                        {
                            checkBox_distance_limit.Checked = (linebreak[1].Trim() == "true" ? true : false);
                        }
                        else if (linebreak[0].Contains("stop_distace"))
                        {
                            numericUpDown_stopposition.Value = Convert.ToDecimal(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("speed"))
                        {
                            numericUpDown_speed.Value = Convert.ToDecimal(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("direction"))
                        {
                            button_direction.ImageIndex = Convert.ToInt32(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("ivindex"))
                        {
                            toolStripTextBox2.Text = linebreak[1].Trim();
                            current_coefficient = (float)Convert.ToDouble(toolStripTextBox2.Text);
                        }
                        else if (linebreak[0].Contains("torque"))
                        {
                            toolStripTextBox1.Text = linebreak[1].Trim();
                            tension = Convert.ToDouble(toolStripTextBox1.Text);
                        }
                    }
                }
            }
        }
        private void setconfig()
        {
            string writeconfig = "";
            writeconfig += "static_interval = " + chart2.ChartAreas[0].AxisX.Interval.ToString() + Environment.NewLine;
            writeconfig += "static_min = " + chart2.ChartAreas[0].AxisX.Minimum.ToString() + Environment.NewLine;
            writeconfig += "static_max = " + chart2.ChartAreas[0].AxisX.Maximum.ToString() + Environment.NewLine;
            writeconfig += "distace_lim = " + (checkBox_distance_limit.Checked ? "true" : "false") + Environment.NewLine;
            writeconfig += "stop_distace = " + numericUpDown_stopposition.Value.ToString() + Environment.NewLine;
            writeconfig += "speed = " + numericUpDown_speed.Value.ToString() + Environment.NewLine;
            writeconfig += "direction = " + button_direction.ImageIndex.ToString() + Environment.NewLine;
            writeconfig += "ivindex = " + toolStripTextBox2.Text + Environment.NewLine;
            writeconfig += "torque = " + toolStripTextBox1.Text;
            System.IO.File.WriteAllText("config.ini", writeconfig);
        }

        private long iCount = 0;//用于刷新界面

        private void updateCurve(DevDataSet devData)
        {
            position.Add((float)devData.pos);
            ad.Add((float)(devData.cur));
        }
        double ad_base = 0;

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "保存文件";
            sfd.Filter = "文本文档(*.txt)|*.txt";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.Copy(backup_file_path, sfd.FileName, true);
            }
        }

        private void setspeedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            numericUpDown_speed.Focus();
            numericUpDown_speed.Select(0, 10);
        }
        string backup_file_path = "";

        private void zGraph1_Load(object sender, EventArgs e)
        {
            zGraph1.m_SySnameX = "位置(m)";
            zGraph1.m_SySnameY = "电流(A)";
            zGraph1.m_SyStitle = "超导带材临界电流位置分布";
        }

        double ivindex = 0.00184;
      

        private void numericUpDown_speed_ValueChanged(object sender, EventArgs e)
        {
            toolStripStatusLabel_speed.Text = "速度：" + numericUpDown_speed.Value.ToString("F2");
        }

        //-----------------------------------------------------------------------------
        private void Init()
        {
            position.Clear();
            ad.Clear();
            ad_base = 0;
            drawCueve = true;
            SetPar();//参数设置

            zGraph1.f_reXY();
            zGraph1.f_ClearAllPix();
            zGraph1.f_LoadOnePix(ref position, ref ad, Color.Red, 1);
            zGraph1.f_AddPix(ref position, ref ad, Color.Red, 1);
            zGraph1.f_Refresh();
        }
        public int clockwise = 0, Dir = 0;
        public double speed = 0;
        string fileName1 = "";
        private  void SetPar()
        {
            setdirection();
            speed = (double)numericUpDown_speed.Value;
            speed = speed / 3600;
            tension =Convert.ToDouble(toolStripTextBox1.Text);
            tension = tension / 1.2;
            fileName1 = textBox1.Text;
            deviceCtrl.setCoff(current_coefficient);
        }

        private bool followlasttime = false;
        bool OpenfromExtern = false;

        private void InitChart()
        {
            Ic_static_x.Clear();
            Ic_static_y.Clear();

            //chart2初始化
            chart2.ChartAreas[0].AxisX.Minimum = 0;
            chart2.ChartAreas[0].AxisX.Maximum = 90;
            chart2.ChartAreas[0].AxisX.Interval = 10;
            chart2.Series[0].Points.AddXY(0, 0);
            chart2.Series[0].Points.Clear();
            chart2.Series[0].Points.DataBindXY(Ic_static_x, Ic_static_y);
            for (double iii = chart2.ChartAreas[0].AxisX.Interval * 0.5 + chart2.ChartAreas[0].AxisX.Minimum; iii < chart2.ChartAreas[0].AxisX.Maximum; iii += chart2.ChartAreas[0].AxisX.Interval)
            {
                Ic_static_x.Add((float)iii);
                Ic_static_y.Add(0);
                chart2.Series[0].Points.AddXY(iii, 0);
            }

        }
        private void button_motor_start_Click(object sender, EventArgs e)
        {
            if (button_motor_start.Text == "开始")
            {
                if (daqTimer.Enabled == true)
                {
                    daqTimer.Enabled = false;
                }


                if (timer1.Enabled == false)
                {
                    timer1.Enabled = true;
                }
                followlasttime = false;
                if (position.Count() > 10)
                {
                    if (MessageBox.Show("是否继续上次测量？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        followlasttime = true;
                    }
                    else
                    {
                        followlasttime = false;
                    }
                }
                if (followlasttime == false)
                {
                    Init();
                }

                if (timer1.Enabled == false) timer1.Enabled = true;

                drawCueve = true;
                
                setconfig();

                SetPar();//参数设置

                zGraph1.f_reXY();
                zGraph1.f_ClearAllPix();
                zGraph1.f_LoadOnePix(ref position, ref ad, Color.Red, 1);
                zGraph1.f_AddPix(ref position, ref ad, Color.Red, 1);
                zGraph1.f_Refresh();

                chart2.Series[0].Points.Clear();

                for (double iii = chart2.ChartAreas[0].AxisX.Interval * 0.5 + chart2.ChartAreas[0].AxisX.Minimum; iii < chart2.ChartAreas[0].AxisX.Maximum; iii += chart2.ChartAreas[0].AxisX.Interval)
                {
                    Ic_static_x.Add((float)iii);
                    Ic_static_y.Add(0);
                    chart2.Series[0].Points.AddXY(iii, 0);
                }

                deviceCtrl.StartRoll_Plane(fileName1,Dir, speed,tension, followlasttime, OpenfromExtern, ad_base, position, ad, backup_file_path);


                daqTimer.Enabled = true;
                button_motor_start.Text = "停止";
            }
            else if (button_motor_start.Text == "停止")
            {
                timer1.Enabled = false;
                drawCueve = false;
                deviceCtrl.StopRoll();
                deviceCtrl.StopDataSaving();
                button_motor_start.Text = "开始";

              // daqTimer.Enabled = false;

            }
        }
        private void Distance_Finish_chekck()
        {
            if (checkBox_distance_limit.Checked)
            {
                double lengthtostop = (double)numericUpDown_stopposition.Value;
                if (Convert.ToDouble(label_curpos.Text) > lengthtostop)
                {
                    //Console.WriteLine(label_curpos.Text);
                    deviceCtrl.StopRoll();
                    deviceCtrl.StopDataSaving();

                    timer1.Enabled = false;

                    if (MessageBox.Show("已到达预设长度", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        button_motor_start.Text = "开始";
                    }
                    else
                    {
                        button_motor_start.Text = "开始";
                    }
                }
            }
        }


        float[] receive_base = new float[5];//存储基础电流

        private void chartshow()
        {
            if (Ic_static_x.Count > 0)
            {
                List<int> display_static_y = new List<int>();
                display_static_y.Clear();
                for (int jjj = 0; jjj < Ic_static_x.Count; jjj++)
                {
                    display_static_y.Add(Ic_static_y[jjj]);
                }
                chart2.Series[0].Points.DataBindXY(Ic_static_x, display_static_y);
            }
        }
        private void torquetextToolStripMenuItem_Click(object sender, EventArgs e)
        {
            double aaa = 0.7;
            clutchtorque = aaa;
        }

        private void updateText(DevDataSet devData)
        {
            if (drawCueve == true)
            {
                label_curpos.Text = devData.pos.ToString("0.000");
                label_curcur.Text = devData.cur.ToString("0.000");
                toolStripStatusLabel_speed.Text = devData.speed.ToString("0.000");
            }
            else
            {
                label_curpos.Text = "0.000";
                label_curcur.Text = devData.cur.ToString("0.000");
                //Console.WriteLine(devData.voltage);
            }
        }

        private void btn_changecoff_Click(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            timer1.Enabled = false;
        }

        bool drawCueve;

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    position.Clear();
        //    ad.Clear();
        //}

        private void 工作目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(Environment.CurrentDirectory + "\\data\\");
        }      

        private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "打开文件";
            ofd.Filter = "文本文档(*.txt)|*.txt";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (ofd.CheckFileExists)
                {
                    backup_file_path = ofd.FileName;
                    string[] a = System.IO.File.ReadAllLines(ofd.FileName);
                    int j = a.Length - 1;

                    ad_base = 0;

                    OpenfromExtern = true;

                    zGraph1.f_ClearAllPix();
                    zGraph1.f_reXY();
                    //zGraph2.f_ClearAllPix();
                    //zGraph2.f_reXY();
                    position.Clear();
                    ad.Clear();

                    chart2.Series[0].Points.Clear();
                    for (int jjjj = Ic_static_y.Count - 1; jjjj >= 0; jjjj--) Ic_static_y[jjjj] = 0;
                    chart2.Series[0].Points.DataBindXY(Ic_static_x, Ic_static_y);

                    for (int i = 0; i < j - 1; i++)
                    {
                        if (a[i] == null || a[i] == "")
                        {

                        }
                        else if (a[i].Contains("Coefficient(V/A):"))
                        {
                            try
                            {
                                current_coefficient = (float)Convert.ToDouble(a[i].Replace("Coefficient(V/A):", "").Trim());
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                        else if (a[i].Contains("Base Current(A):"))
                        {
                            try
                            {
                                ad_base = (float)Convert.ToDouble(a[i].Replace("Base Current(A):", "").Trim());
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                        else if (a[i].Contains('e') || a[i].Contains('m') || !a[i].Contains('\t'))
                        { }
                        else
                        {
                            try
                            {
                                string[] b = a[i].Split('\t');
                                if (b.Length == 4)
                                {
                                    //receive[0].Add(float.Parse(b[0]));
                                    position.Add(float.Parse(b[1]));
                                    ad.Add(float.Parse(b[2]));

                                    double iiii = Convert.ToDouble(b[2]);
                                    if (iiii >= chart2.ChartAreas[0].AxisX.Maximum)
                                    {
                                    }
                                    else if (iiii < chart2.ChartAreas[0].AxisX.Minimum)
                                    {
                                    }
                                    else
                                    {
                                        Ic_static_y[(int)((iiii - chart2.ChartAreas[0].AxisX.Minimum) / chart2.ChartAreas[0].AxisX.Interval)] += 1;
                                    }
                                }
                            }
                            catch (Exception ex)
                            { }
                        }
                    }
                    zGraph1.f_LoadOnePix(ref position, ref ad, Color.Red, 1);
                    zGraph1.f_Refresh();

                    List<int> display_static_y = new List<int>();
                    display_static_y.Clear();
                    for (int jjj = 0; jjj < Ic_static_x.Count; jjj++)
                    {
                        display_static_y.Add(Ic_static_y[jjj]);
                    }
                    chart2.Series[0].Points.DataBindXY(Ic_static_x, display_static_y);
                    toolStripStatusLabel_ivindex.Text = current_coefficient.ToString();
                }
            }
        }

        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "保存文件";
            sfd.Filter = "文本文档(*.txt)|*.txt";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.Copy(backup_file_path, sfd.FileName, true);
            }
        }

        double tension = 0.0;
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            tension = Convert.ToDouble(toolStripTextBox1.Text);
            if (tension > 5) tension = 5;
        }

        float current_coefficient = 0;//1个电流系数

        private void 确认系数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            current_coefficient = (float)Convert.ToDouble(toolStripTextBox2.Text);
            toolStripStatusLabel_ivindex.Text = "IV系数：" + current_coefficient.ToString();
        }

        private void 统计设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            form_staticset frm_stat = new form_staticset(chart2.ChartAreas[0].AxisX.Minimum, chart2.ChartAreas[0].AxisX.Maximum, chart2.ChartAreas[0].AxisX.Interval);
            frm_stat.ShowDialog();
            chart2.ChartAreas[0].AxisX.Minimum = frm_stat.low_limit;
            chart2.ChartAreas[0].AxisX.Maximum = frm_stat.high_limit;
            chart2.ChartAreas[0].AxisX.Interval = frm_stat.interval;
        }

       
        private void button_direction_Click(object sender, EventArgs e)
        {
            button_direction.ImageIndex = 1 - button_direction.ImageIndex;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void setdirection()
        {
            if (button_direction.ImageIndex == 0) { Dir = 0; }
            else { Dir = 1; }
        }
    }
}